﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace MetaDesigner
{
    /// <summary>
    /// Interaction logic for SPFetchGUI.xaml
    /// </summary>
    public partial class SPFetchGUI : Window
    {
        private delegate void NoArgDelegate();

        /// <summary>
        /// Initializes a new instance of the <see cref="SPFetchGUI"/> class.
        /// </summary>
        public SPFetchGUI()
        {
            InitializeComponent();
            ShowInTaskbar = false;
            Topmost = true;
            ResizeMode = ResizeMode.NoResize;
        }
        /*
        private void SaveFileBrowse_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.DefaultExt = ".xml";
            dlg.Filter = "XML Files|*.xml";
            dlg.OverwritePrompt = true;
            Nullable<bool> res = dlg.ShowDialog();
            if (res == true)
            {
                pathField.Text = dlg.FileName;
            }
        }*/

        /// <summary>
        /// Handles the Click event of the Fetch control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void Fetch_Click(object sender, RoutedEventArgs e)
        {
            String url = urlField.Text;
            //String path = pathField.Text;
            NoArgDelegate fetchThread = new NoArgDelegate(new Action(() => { Fetch(url); }));
            fetchThread.BeginInvoke(null, null);
            urlField.IsEnabled = false;
            //pathField.IsEnabled = false;
            //BrowseBtn.IsEnabled = false;
            FetchBtn.IsEnabled = false;
            FetchBtn.Content = "Fetching...";
        }

        /// <summary>
        /// Fetches SharePoint data from the specified URL.
        /// </summary>
        /// <param name="url">The URL.</param>
        private void Fetch(string url)
        {
            if (DataModel.SaveFile.SPDumpElement != DataModel.SaveFile.Default_SPDumpElement)
            {
                MessageBoxResult res = MessageBox.Show("The current project file already has data from a SharePoint site in it. Performing this action will overwrite the current SharePoint data and could possibly cause conflicts with currently defined Content Types and Site Columns. Are you sure you wish to perform this action?", "WARNING", MessageBoxButton.YesNo);
                if (res == MessageBoxResult.No)
                {
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        //System.Windows.Clipboard.SetText(result);
                        this.Close();
                    }));
                }
            }

            try
            {
                //get a string representation of the XML for SPDump
                String result = new SPFetch.Program().run(url);

                //create a new XmlDocument and load the result of the SPFetch
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(result);

                //import the SPDump node to the savefile XmlDocument and replace the SPDumpElement as an XmlElement
                DataModel.SaveFile.SPDumpElement = DataModel.SaveFile.SPDumpElement.OwnerDocument.ImportNode(doc.GetElementsByTagName("SPDump")[0], true) as System.Xml.XmlElement;
                DataModel.SaveFile.reloadDump();
                DataModel.SaveFile.SPDump_SiteUrl = url;

                //close the SPfetch window if successful
                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    //System.Windows.Clipboard.SetText(result);
                    this.Close();
                }));
            }
            catch (Exception ex)
            {
                DataModel.Log.Append("Fetch_Click exception: " + ex.Message).AppendLine();

                this.Dispatcher.BeginInvoke(new Action(() =>
                {
                    MessageBox.Show("Error: " + ex.Message);

                    //pathField.IsEnabled = true;
                    //BrowseBtn.IsEnabled = true;
                    urlField.IsEnabled = true;
                    FetchBtn.IsEnabled = true;
                    FetchBtn.Content = "Fetch";
                }));
            }
        }

        /// <summary>
        /// Handles the Loaded event of the urlField control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void urlField_Loaded(object sender, RoutedEventArgs e)
        {
            urlField.Text = "http://localhost";
            urlField.Focus();
            urlField.Select(urlField.Text.Length, 0);
        }
    }
}
